package cn.iocoder.yudao.framework.mybatis.core.mapper;

import cn.iocoder.yudao.framework.common.exception.ApplicationException;
import cn.iocoder.yudao.framework.common.exception.enums.GlobalExceptionEnum;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CommonMapper {

    private static final Logger LOG = LoggerFactory.getLogger(CommonMapper.class);
    private SqlSession sqlSession;

    public CommonMapper(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }

    public Connection getConnection() throws SQLException {
        return sqlSession.getConfiguration().getEnvironment().getDataSource().getConnection();
    }

    public Long getTotalCount(String sql, List<Object> parms) {
        PreparedStatement ps = null;
        ResultSet rs = null;
        Connection con = null;
        try {
            con = getConnection();
            ps = con.prepareStatement(sql);
            setParmsToPreparedStatement(ps, parms);
            rs = ps.executeQuery();
            if (rs.next()) {
                return rs.getLong(1);
            }
        } catch (Exception ex) {
            throw new ApplicationException(GlobalExceptionEnum.SYS_DATABASE_ERROR, ex);
        } finally {
            closeResource(con, ps, rs);
        }
        return null;
    }

    public Integer execute(String sql, List<Object> parms) {
        PreparedStatement ps = null;
        Connection con = null;
        try {
            con = getConnection();
            ps = con.prepareStatement(sql);
            setParmsToPreparedStatement(ps, parms);
            return ps.executeUpdate();
        } catch (Exception ex) {
            throw new ApplicationException(GlobalExceptionEnum.SYS_DATABASE_ERROR, ex);
        } finally {
            closeResource(con, ps, null);
        }
    }

    public List<Map<String, Object>> listMaps(String sql, List<String> cols, List<Object> parms) {
        return this.listMapsByPage(sql, cols, 0, 0, parms);
    }

    public List<Map<String, Object>> listMapsByPage(String sql, List<String> cols, int page, int rows, List<Object> parms) {
        final List<Map<String, Object>> result = new ArrayList<>();
        final StringBuilder sb = new StringBuilder(sql);
        if (page != 0 && rows != 0) {
            sb.append(" limit ").append((page - 1) * rows).append(",").append(rows);
        }

        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        Connection con = null;
        try {
            con = getConnection();
            preparedStatement = con.prepareStatement(sb.toString());
            setParmsToPreparedStatement(preparedStatement, parms);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                Map<String, Object> map = new HashMap<>();
                for (String col : cols) {
                    map.put(col, resultSet.getObject(col));
                }
                result.add(map);
            }
            return result;
        } catch (SQLException ex) {
            throw new ApplicationException(GlobalExceptionEnum.SYS_DATABASE_ERROR, ex);
        } finally {
            closeResource(con, preparedStatement, resultSet);
        }
    }

    public static void closeResource(Connection con, Statement st, ResultSet rs) {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                LOG.error("close Connection Error", e);
            }
        }
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                LOG.error("close Statement Error", e);
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.error("close ResultSet error", e);
            }
        }
    }

    public static void setParmsToPreparedStatement(PreparedStatement ps, List<Object> parms) throws SQLException {
        if (parms != null && parms.size() > 0) {
            int index = 1;
            for (Object parm : parms) {
                ps.setObject(index, parm);
                index++;
            }
        }
    }
}
